# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


# class WallpaperPipeline(object):
#     def process_item(self, item, spider):
#         return item

import scrapy
from scrapy.pipelines.images import ImagesPipeline
from scrapy.exceptions import DropItem

class WallpaperPipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        item = item
        img_url = item['img_url']
        img_name = item['img_path']+item['img_name']+'.jpg'
        yield scrapy.Request(img_url,meta={'img_name':img_name})

    def file_path(self, request, response=None, info=None):
        filename = request.meta['img_name']
        # folder = item['title']
        # folder_strip = folder.strip()
        # image_guid = request.url.split('/')[-1]
        # filename = u'imge/{0}/{1}'.format(folder_strip, image_guid)
        return filename

    def item_completed(self, results, item, info):
        image_path = [x['path'] for ok, x in results if ok]
        if not image_path:
            print('失败')
            raise DropItem("Item contains no images")
        print("成功")
        item['image_paths'] = item['img_path']+item['img_name']+'.jpg'
        return item